/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
        TreeNode* ret = nullptr;
        TreeNode* head = ret;
        bool flag = false;
        Dfs(root1, root2, ret, head, flag);
        return head;
    }

	/* 对指针的引用 */
     void Dfs(TreeNode* root1, TreeNode* root2, TreeNode*& ret, TreeNode*& head, bool& flag)
    {
        if ((root1 != nullptr) && (root2 != nullptr)) {
            TreeNode* newNode = new TreeNode(root1->val + root2->val);
            ret = newNode;
            if (!flag) {
                head = ret;
                flag = true;
            }
            Dfs(root1->left, root2->left, ret->left, head, flag);
            Dfs(root1->right, root2->right, ret->right, head, flag);
        } else if ((root1 == nullptr) && (root2 != nullptr)) {
            TreeNode* newNode = new TreeNode(root2->val);
            ret = newNode;
            if (!flag) {
                head = ret;
                flag = true;
            }
            Dfs(nullptr, root2->left, ret->left, head, flag);
            Dfs(nullptr, root2->right, ret->right, head, flag);
        } else if ((root1 != nullptr) && (root2 == nullptr)) {
            TreeNode* newNode = new TreeNode(root1->val);
            ret = newNode;
            if (!flag) {
                head = ret;
                flag = true;
            }
            Dfs(root1->left, nullptr, ret->left, head, flag);
            Dfs(root1->right, nullptr, ret->right, head, flag);
        } else {
            ret = nullptr;
        }
    }
};